<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 300px;
        height: 300px;
        border: 1px solid purple;
        background-color: skyblue;
        margin: 50px 0;
      }
    </style>
  </head>
  <body>
    <button>发送ajax</button>
    <div class="box"></div>
    <script>
      var btn = document.querySelector('button')
      var box = document.querySelector('.box')
      btn.onclick = function () {
        var xhr = new XMLHttpRequest()
        // 超时2s的操作
        xhr.timeout = 2000
        xhr.ontimeout = function () {
          alert('请求超时，请稍后重试')
        }
        // 网络异常
        xhr.onerror = function () {
          alert('您的网络似乎出了点问题')
        }
        // 路径后加?+Date.now() 解决ie无法及时传输数据问题
        xhr.open('get', 'http://127.0.0.1:8080/delay')
        xhr.send()
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
              box.innerHTML = xhr.response
            }
          }
        }
      }
    </script>
  </body>
</html>
